<template>
  <el-button
    type="primary"
    text
    bg
    :disabled="disabled"
    @click="getCode">
    {{ btnText }}
  </el-button>
</template>

<script setup>
  import { ElMessage } from 'element-plus';

  import { sendUpdateVerifyCode } from '@/api/index';

  import { useUserStore } from '@/stores/user';
  const userStore = useUserStore();

  function getCode() {
    sendUpdateVerifyCode({
      mobile: userStore.user.mobile
    }).then(res => {
      countDownFn();
      ElMessage.success('验证码已发送');
    });
  }

  let btnText = ref('获取验证码');
  let times = ref(60);
  let disabled = ref(false);

  // 倒计时
  function countDownFn() {
    let t = setInterval(() => {
      if (times.value <= 1) {
        clearInterval(t);
        times.value = 60;
        disabled.value = false;
        btnText.value = '重新获取';
      } else {
        disabled.value = true;
        times.value--;
        btnText.value = `${times.value}s`;
      }
    }, 1000);
  }
</script>

<style lang="scss" scoped></style>
